<template>
  <div class="comment-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>评论审核</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleBatchAudit(1)" :disabled="!selectedComments.length">
              批量通过
            </el-button>
            <el-button type="danger" @click="handleBatchAudit(2)" :disabled="!selectedComments.length">
              批量拒绝
            </el-button>
          </div>
        </div>
      </template>

      <!-- 评论列表 -->
      <el-table
        v-loading="loading"
        :data="commentList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="评论ID" width="80" />
        <el-table-column prop="productName" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column label="用户信息" width="150">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.avatar">
                {{ row.nickname?.charAt(0) }}
              </el-avatar>
              <span class="nickname">{{ row.isAnonymous ? '匿名用户' : row.nickname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评分" width="120">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="200" show-overflow-tooltip />
        <el-table-column label="评论图片" width="150">
          <template #default="{ row }">
            <div class="image-preview" v-if="row.images && row.images.length">
              <el-image
                v-for="(img, index) in row.images"
                :key="index"
                :src="img"
                :preview-src-list="row.images"
                fit="cover"
                class="preview-image"
              />
            </div>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="评论时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="success"
                link
                @click="handleAudit(row, 1)"
              >通过</el-button>
              <el-button
                type="danger"
                link
                @click="handleAudit(row, 2)"
              >拒绝</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditDialogTitle"
      width="500px"
    >
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核备注">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核备注（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPendingComments, auditComment, batchAuditComments } from '@/api/admin'

// 状态定义
const loading = ref(false)
const submitting = ref(false)
const commentList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedComments = ref([])

// 审核相关
const auditDialogVisible = ref(false)
const auditDialogTitle = ref('')
const auditForm = ref({
  commentIds: [],
  status: null,
  remark: ''
})

// 获取评论列表
const fetchComments = async () => {
  try {
    loading.value = true
    const res = await getPendingComments({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (res?.code === 200) {
      commentList.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.warning(res?.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 处理表格选择
const handleSelectionChange = (selection) => {
  selectedComments.value = selection
}

// 处理单个审核
const handleAudit = (row, status) => {
  auditForm.value = {
    commentIds: [row.id],
    status,
    remark: ''
  }
  auditDialogTitle.value = status === 1 ? '通过评论' : '拒绝评论'
  auditDialogVisible.value = true
}

// 处理批量审核
const handleBatchAudit = (status) => {
  if (!selectedComments.value.length) {
    ElMessage.warning('请选择要审核的评论')
    return
  }

  auditForm.value = {
    commentIds: selectedComments.value.map(item => item.id),
    status,
    remark: ''
  }
  auditDialogTitle.value = status === 1 ? '批量通过评论' : '批量拒绝评论'
  auditDialogVisible.value = true
}

// 提交审核
const submitAudit = async () => {
  try {
    submitting.value = true
    const res = await batchAuditComments(auditForm.value)
    
    if (res?.code === 200) {
      ElMessage.success('审核成功')
      auditDialogVisible.value = false
      fetchComments()
    } else {
      ElMessage.error(res?.message || '审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  } finally {
    submitting.value = false
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchComments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchComments()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '暂无'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 初始化
onMounted(() => {
  fetchComments()
})
</script>

<style scoped>
.comment-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.nickname {
  font-size: 14px;
}

.image-preview {
  display: flex;
  gap: 4px;
}

.preview-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

:deep(.el-rate) {
  margin-top: 2px;
}
</style> 